package com.heatup.apt.management.pay;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.model.order.OrderRefund;

/**
 * 退款状态查询
 * 
 * @author jixiangyun 2016年10月2日 下午6:18:54
 */
public class RefundSelect {
	private java.util.Timer timer = null;
	 private ServletContext context = null;
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	
	
	public void updateOrderRefund() {
		// 查询所有订单状态不是 成功的订单
		List<OrderRefund> listR = orderInfoMapper.getOrderRefundList();
		for (OrderRefund orderR : listR) {
			Map<String, Object> map = selectRefund(orderR.getRefundNo());
			String result_code = (String) map.get("result_code");
			String refund_status = (String) map.get("refund_status_0");
			if ("SUCCESS".equals(result_code)) {
				orderR.setRefundStatus(refund_status);
				int sta = orderInfoMapper.updateOrderRefund(orderR);
				System.out.println("状态修改>>>>>>>>>>>>>>>>>>>>>>>>>>");
			}
		}

	}
	// 根据订单号查询订单状态
	public static Map<String, Object> selectRefund(String refund_id) {
		String nonce_str = UUID.randomUUID().toString().substring(0, 10);// 随机字符串
		// 开发者ID
		String appid =  String.valueOf(ManageConfigPropertiesUtil.get("wechat_appid")).trim();  // "wx65db45e85c1be9c4";
		// appsecret
		String appsecret = String.valueOf(ManageConfigPropertiesUtil.get("wechat_appsecret")).trim();//"3816ac8f220a3e9150fbab7321064d45";
		String refund_account =String.valueOf(ManageConfigPropertiesUtil.get("wechat_refund_account")).trim();  // "REFUND_SOURCE_RECHARGE_FUNDS";
		// 商户号
		String mch_id =String.valueOf(ManageConfigPropertiesUtil.get("wechat_mch_id")).trim(); //"1369211002";
		String op_user_id = mch_id;// 就是MCHID
		// 商户号
		String partnerkey = String.valueOf(ManageConfigPropertiesUtil.get("wechat_partnerkey")).trim(); //"youfang20161001youfang2016100101";
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("refund_id", refund_id);
		RequestHandler reqHandler = new RequestHandler(null, null);
		reqHandler.init(appid, appsecret, partnerkey);
		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<mch_id>" + mch_id + "</mch_id>" + "<nonce_str>"
				+ nonce_str + "</nonce_str>" + "<sign><![CDATA[" + sign + "]]></sign>" + "<refund_id>" + refund_id
				+ "</refund_id>" + "</xml>";
		String createOrderURL = String.valueOf(ManageConfigPropertiesUtil.get("wechat_create_refund_query_url")).trim();
				//"https://api.mch.weixin.qq.com/pay/refundquery";
		Map<String, Object> mapData = null;
		try {
			String refundResult = ClientCustomSSL.doRefund(createOrderURL, xml);
			mapData = toXML(refundResult);
			if ("SUCCESS".equals(mapData.get("result_code"))) {
				System.out.println("退款产生的json字符串：" + "\n" + refundResult);
				return mapData;
			} else {
				return mapData;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return mapData;
	}

	/**
	 * 将String格式的xml转换为map
	 * 
	 * @param xml
	 * @return
	 */
	public static Map<String, Object> toXML(String xml) {
		Map<String, Object> map = new HashMap<String, Object>();
		Document dom = null;
		try {
			dom = DocumentHelper.parseText(xml);
			Element root = dom.getRootElement();
			String return_code = root.element("return_code").getText();
			String return_msg = root.element("return_code").getText();
			String result_code = root.element("result_code").getText();
			map.put("return_code", return_code);
			map.put("return_msg", return_msg);
			map.put("result_code", result_code);
			if ("FAIL".equals(result_code)) {
				String err_code = root.element("err_code").getText();
				String err_code_des = root.element("err_code_des").getText();
				map.put("err_code", err_code);
				map.put("err_code_des", err_code_des);
				return map;
			}
			map.put("transaction_id", root.element("transaction_id").getText());
			map.put("out_trade_no", root.element("out_trade_no").getText());
			map.put("out_refund_no", root.element("out_refund_no_0").getText());
			map.put("refund_id_0", root.element("refund_id_0").getText());
			map.put("refund_status", root.element("refund_status_0").getText());
			map.put("refund_channel", root.element("refund_channel_0").getText());
			map.put("refund_fee", root.element("refund_fee").getText());
			map.put("total_fee", root.element("total_fee").getText());
			map.put("cash_fee", root.element("cash_fee").getText());
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 查询订单状态
	 * 
	 * @return
	 */
	public static Map orderQuery(String trade_no) {
		String nonce_str = Sha1Util.getNonceStr();
		SortedMap<String, String> beanMap = new TreeMap();
		beanMap.put("appid", ManageConfigPropertiesUtil.getString("wechat_appid"));
		beanMap.put("mch_id", ManageConfigPropertiesUtil.getString("wechat_mch_id"));
		beanMap.put("nonce_str", nonce_str);
		beanMap.put("transaction_id",trade_no);
		String sign = Sha1Util.genWXPackageSign(beanMap);
		String xml = "<xml>" + 
					 "<appid>"+ManageConfigPropertiesUtil.getString("wechat_appid")+"</appid>" + 
					 "<mch_id>"+ManageConfigPropertiesUtil.getString("wechat_mch_id")+"</mch_id>" + 
					 "<nonce_str>" + nonce_str + "</nonce_str>" + 
					 "<transaction_id>" + trade_no + "</transaction_id>" + 
					 "<sign>" + sign + "</sign>" + 
					 "</xml>";
		try {
			String refundResult = ClientCustomSSL.doRefund(ManageConfigPropertiesUtil.getString("wechat_orderquery"), xml);
			Map result = XMLUtil.doXMLParse(refundResult);
			System.out.println(refundResult);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		/*selectRefund("2008782001201609270477658817");*/
		RefundSelect t = new RefundSelect();
		Map map = t.quertRefundStatus("4000712001201611099216561997");//t.orderQuery("4006652001201610288016305969");
	}
	
	/**
	 * 退款接口查询
	 * @param trade_no
	 * @return
	 */
	public Map<String,Object> quertRefundStatus(String trade_no){
		String url = "https://api.mch.weixin.qq.com/pay/refundquery";
		String nonce_str = Sha1Util.getNonceStr();
		SortedMap<String, String> beanMap = new TreeMap();
		beanMap.put("appid", ManageConfigPropertiesUtil.getString("wechat_appid"));
		beanMap.put("mch_id", ManageConfigPropertiesUtil.getString("wechat_mch_id"));
		beanMap.put("nonce_str", nonce_str);
		beanMap.put("transaction_id",trade_no);
		String sign = Sha1Util.genWXPackageSign(beanMap);
		String xml = "<xml>" + 
					 "<appid>"+ManageConfigPropertiesUtil.getString("wechat_appid")+"</appid>" + 
					 "<mch_id>"+ManageConfigPropertiesUtil.getString("wechat_mch_id")+"</mch_id>" + 
					 "<transaction_id>"+trade_no+"</transaction_id>"+
					 "<sign>" + sign + "</sign>" + 
					 "</xml>";
		try {
			String refundResult = ClientCustomSSL.doRefund(url, xml);
			Map result = XMLUtil.doXMLParse(refundResult);
			System.out.println(refundResult);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
